package com.wchen.project.zk.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * @Desc:   使用 Curator 删除节点
 * @author: cww
 * @DateTime: 2020-01-23 22:07
 */

public class ZkDeleteDataByCurator {
    static String path = "/zk-book/c1";
    static CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("home:2181")
            .sessionTimeoutMs(5000)
            .retryPolicy(new ExponentialBackoffRetry(1000,3))
            .build();

    public static void main(String[] args) throws Exception {
        client.start();
        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, "init".getBytes());
        Stat stat = new Stat();
        client.getData().storingStatIn(stat).forPath(path);
        client.delete().deletingChildrenIfNeeded().withVersion(stat.getVersion()).forPath(path);
    }

    public static void delteFunction() throws Exception {
        // 删除一个节点
        client.delete().forPath(path);
        // 删除一个节点，并递归删除其所有子节点
        client.delete().deletingChildrenIfNeeded().forPath(path);
        // 删除一个节点，强制指定版本删除
        client.delete().withVersion(1).forPath(path);
        // 删除一个节点，强制保证删除,
        // 注意：guaranteed() 接口只是一个保障措施，只要客户端会话有效，那么 Curator
        // 会在后台持续进行删除操作，直到节点删除成功
        client.delete().guaranteed().forPath(path);
    }
}
